from rest_framework.response import Response
from common.views.base_views import BaseAPIView
from apps.user.models import AdministrativeArea
from apps.product.models import *
from sdks.mredis import SortedSet
from tuntun.settings import REDIS_KEY_USER_SEARCH_KEYS
from .models import SystemSetting
from django.http import HttpResponse
from tuntun.settings import HOST
from django.shortcuts import render
from urllib.parse import urlparse, parse_qs
from django.db import transaction
from common import time_rest
from apps.product.views import val
from tuntun.settings import APP_DOWNLOAD_LINK
from django.http import HttpResponseRedirect
import requests
from apps.mix.dbviews import ViewUserProduct
import json
from apps.product.models import MarketOrder
# Create your views here.

class SystemInfo(BaseAPIView):
    permission_classes = ()
    def get(self, request, *args, **kwargs):
        ss = SystemSetting.objects.first()
        ret = {
            'kefu_phone': ss.kefu_phone if ss.kefu_phone else '',
            'jubao_phone': ss.jubao_phone if ss.kefu_phone else '',
        }
        return Response(ret)


class SystemAdministrativeAreaDataView(BaseAPIView):
    permission_classes = ()
    def get(self, request, *args, **kwargs):
        self.resp = {
            "provinces": [
                {"id": p.id, "name": p.name, "zip_code": p.zip_code, "parent_id": p.parent_id}
                for p in AdministrativeArea.objects.filter(level=AdministrativeArea.Level.P.name)],
            "cities": [
                {"id": c.id, "name": c.name, "zip_code": c.zip_code, "parent_id": c.parent_id}
                for c in AdministrativeArea.objects.filter(level=AdministrativeArea.Level.C.name)],
        }
        return Response(self.resp)


class DistrictsDataView(BaseAPIView):
    permission_classes = ()

    def get(self, request, *args, **kwargs):
        self.resp = {
            "districts": [{"id": d.id, "name": d.name, "zip_code": d.zip_code}
                          for d in AdministrativeArea.objects.filter(level=AdministrativeArea.Level.X.name,
                                                                     parent_id=kwargs['id'])]
        }
        return Response(self.resp)


class WholeSearchView(BaseAPIView):
    """
    整站搜索
    GET     /system/whole-search?key=湾
    """
    permission_classes = ()

    def get(self, request, *args, **kwargs):
        user = request.user
        key = request.GET.get('key').strip()
        # Process Search Rank Data
        search_history = SortedSet(REDIS_KEY_USER_SEARCH_KEYS)
        if search_history.rank(key):
            search_history.increment(key)
        else:
            search_history.add(**{key: 1})

        resp = {"brands": {}, "products": {}}

        products = Product.objects.filter(name__icontains=key, status__in=[Product.ProductStatus.PRE_SALE_ING.name, Product.ProductStatus.PRE_SALE_END.name])
        re_product = {"count": products.count(), "items": []}
        for product in products:
            tmp = product.product_detail()
            if MarketOrder.objects.filter(product=product, status=MarketOrder.Status.ING.name):
                have_market_order = True
            else:
                have_market_order = False
            tmp['have_market_order'] = have_market_order
            re_product['items'].append(tmp)
        resp["products"] = re_product

        brands = Brand.objects.filter(name__icontains=key)
        re_brand = {"count": brands.count(), "items": []}
        for brand in brands:
            re_brand['items'].append({
                "id": brand.id,
                "logo": brand.logo,
                "name": brand.name,
                "attention_count": brand.attention_count,
                "is_attention": brand.is_attention(user.id)
            })
            resp["brands"] = re_brand
        return Response(resp)


class ListHotSearchView(BaseAPIView):
    permission_classes = ()

    def get(self, request, *args, **kwargs):
        search_history = SortedSet(REDIS_KEY_USER_SEARCH_KEYS)
        keys = search_history.range_desc(0, 10, withscores=True)
        resp = {}
        resp['count'] = len(keys)
        resp['items'] = [{'key': e[0], 'score': e[1]} for e in keys]
        return Response(resp)


class GetAppServiceProtocolView(BaseAPIView):
    permission_classes = ()

    def get(self, request, *args, **kwargs):
        resp = {'content': SystemSetting.get_app_service_protocol()}
        return Response(resp)


class MakeGbUniqueQrcodesView(BaseAPIView):
    permission_classes = ()
    def get(self, request, *args, **kwargs):
        id = kwargs.get('id')
        product = Product.objects.get(pk=id)
        product_fields = product.get_unique_code()
        last_no_int_fields = None
        unique_codes = []
        for i in range(product.publish_count):
            last_no_int_fields = GoodsBlock.get_next_no_int_fields(last_no_int_fields)
            last_no_fields = [chr(last_no_int_fields[k]) if k in [0, 1] else int_2_2d(last_no_int_fields[k]) for k in
                              range(len(last_no_int_fields))]
            no = ''.join(last_no_fields)
            uc = ''.join(product_fields)+no
            uc_link = HOST + '/pages/blockChainInfo.html?unique_code=' + uc + '&host=' + HOST.split('/')[-1] + '&protocol=' + HOST.split(':')[0]
            unique_codes.append(uc_link)
        return HttpResponse('<br>'.join(unique_codes))


class BatchInRepoView(BaseAPIView):
    permission_classes = ()
    def get(self, request, *args, **kwargs):
        import datetime
        import time
        from apps.repo.models import Repo, StoreUnitThree
        from apps.mix.tasks import async_product_in_repo
        id = kwargs.get('id')
        product = Product.objects.get(pk=id)
        t = async_product_in_repo.delay(product.id)
        product.in_repo_task_id = t.id
        product.save()
        return HttpResponse('数量：%d，正在入库，请返回产品列表刷新状态' % product.publish_count)

class ProductLockStoreUnit(BaseAPIView):
    permission_classes = ()
    def get(self, request, *args, **kwargs):
        import datetime
        import time
        id = kwargs.get('id')
        product = Product.objects.get(pk=id)
        # 初始化存储位置
        from apps.mix.tasks import async_lock_store_unit
        t = async_lock_store_unit.delay(product.id)
        product.init_store_unit_task_id = t.id
        product.save()
        return HttpResponse('数量：%d，正在初始化，请返回产品列表刷新状态' % product.publish_count)

class ShareView(BaseAPIView):
    """
    分享
    """
    permission_classes = ()
    def get(self, request, *args, **kwargs):
        img_id = kwargs.get('id')
        title = request.GET.get('title')

        pic = PublicFile.objects.filter(pk=img_id).first()
        if not pic:
            return HttpResponse('资源不存在')

        return render(request, 'shares.html', {'img_src': pic.url, 'title': title})


class SharePreSaleProductView(BaseAPIView):
    """分享产品预售详情"""
    permission_classes = ()
    def get(self, request, *args, **kwargs):
        import time
        import datetime
        from apps.repo.models import Repo
        context = {}
        id = kwargs.get('id')
        pro = Product.objects.filter(id=id).first()
        if not pro:
            return HttpResponse('产品不存在')
        repo = Repo.objects.filter(id=pro.repo_id)[0]
        images = ProductLongImage.objects.filter(product_id=pro.id).order_by("order")
        images_url = []
        for img in images:
            images_url.append({
                "img_url": img.banner_url
            })
        pre_sale_rest_times = pro.pre_sale_end_time - pro.pre_sale_start_time
        tr = time_rest(pre_sale_rest_times.total_seconds())
        pro_info = {
            "logo": pro.logo,
            "name": pro.name,
            "brand_id": pro.brand.id,
            "brand": pro.brand.name,
            "brand_logo": pro.brand.logo,
            "brand_attention_count": pro.brand.attention_count,
            "store_id": pro.brand.store.id,
            "store": pro.brand.store.name,
            "stock": pro.stock,
            "pre_sale_price": pro.pre_sale_price,
            "pre_sale_start_end": '%s-%s' % (
                pro.pre_sale_start_time.strftime('%Y.%m.%d'), pro.pre_sale_end_time.strftime('%m.%d')),
            "pre_sale_rest_times": "%s天%s时%s分" % (int_2_2d(tr.days), int_2_2d(tr.hours), int_2_2d(tr.minutes)),
            "id": pro.id,
            "video_banner": pro.video,
            "specification": pro.specification,
            "kind": pro.kind,
            "material": pro.material,
            "repo": repo.name,
            "age": pro.age,
            "publish_count": pro.publish_count,
            "technology": pro.technology,
            "tea_mountain": pro.tea_mountain,
            "altitude": pro.altitude,
            "ancient_tea_tree_count": pro.ancient_tea_tree_count,
            "year_avg_temperature": pro.year_avg_temperature,
            "year_avg_precipitation": pro.year_avg_precipitation,
            "made_in": pro.made_in,
            "long_images": images_url,
            "status": pro.status,
            "status_map": dict(Product.ProductStatus.get_choices()),
            "keeping_count": pro.keeping_count,
            "avg_price": pro.avg_price,
            "up_down_percent": pro.up_down_percent,
        }
        # comments
        cmts = []
        offset = request.GET.get('offset', -1)
        limit = request.GET.get('limit', -1)
        offset, limit = val(offset, limit)
        count, product_comments = ProductComment.objects.filter_by_page(offset, limit, product_id=pro.id)
        for p_com in product_comments:
            pics = ProductCommentPictures.objects.filter(product_comment=p_com.id).order_by("order")
            pictures = []
            for p in pics:
                pictures.append({
                    "img_url": p.picture
                })
            user = User.objects.filter(id=p_com.user_id).first()
            cmts.append({
                "user_id": p_com.user_id,
                "nickname": user.nickname,
                "user_avatar": user.avatar,
                "content": p_com.content,
                "add_time": time.strftime('%Y-%m-%d', time.localtime(p_com.add_timestamp)),
                "pictures": pictures,
            })
        pro_info['comments'] = cmts
        context.update(pro_info)
        context['download_link'] = APP_DOWNLOAD_LINK
        return render(request, 'system/AdvanceSaleDetails.html', context)


class ShareUserTeaRepoStatistics(BaseAPIView):
    permission_classes = ()
    def get(self, request, *args, **kwargs):
        user_id = kwargs.get('id')
        other_user = User.objects.filter(id=user_id).first()
        if not other_user:
            raise HttpResponse('用户不存在')

        other_user.goods_block_count = GoodsBlock.objects.filter(
            ~Q(trade_type=GoodsBlock.TradeType.TAKE_OUT.name), owner_user_id=other_user.id).count()
        other_user.save()
        resp = {
            "nickname": other_user.nickname,
            "avatar": other_user.avatar,
            "open_repo": other_user.open_repo,
            "trade_count": other_user.trade_num,
            "goods_block_count": other_user.goods_block_count,
        }

        products = ViewUserProduct.objects.filter(owner_user_id=user_id)
        resp["products"] = [p.as_dict() for p in products]
        resp.update(other_user.get_tea_repo_statistics())
        resp['today_total_value_data'] = json.dumps(resp['today_total_value_data'])
        resp['current_week_total_value_data'] = json.dumps(resp['current_week_total_value_data'])
        resp['current_month_total_value_data'] = json.dumps(resp['current_month_total_value_data'])
        resp['nickname'] = other_user.nickname
        resp['download_link'] = APP_DOWNLOAD_LINK
        return render(request, 'system/businessCard.html', resp)


class ShareGiftView(BaseAPIView):
    permission_classes = ()
    def get(self, request, *args, **kwargs):
        context = {}
        id = kwargs.get('id')
        order = Order.objects.get(pk=id)
        context['order'] = order
        context['title'] = '赠送'
        return render(request, 'system/gift.html', context)